package com.yf.modules.system.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.Utils.CacheKey;
import com.yf.Utils.FileUtil;
import com.yf.Utils.RedisUtils;
import com.yf.dao.UserJobMapper;
import com.yf.dao.UserRoleMapper;
import com.yf.domain.security.Job;
import com.yf.domain.security.Role;
import com.yf.domain.security.User;
import com.yf.dao.UserMapper;
import com.yf.model.query.UserQueryCriteria;
import com.yf.modules.system.manager.UserCacheManager;
import com.yf.modules.system.service.api.UserService;
import com.yf.response.exceptions.BusinessException;
import com.yf.response.exceptions.UserValidateException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author chentianwei
 * @date 2023/5/22 15:03
 * @description userService实现曾
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final UserRoleMapper userRoleMapper;
    private final UserJobMapper userJobMapper;
    private final RedisUtils redisUtils;
    private final UserCacheManager userCacheManager;

    private final PasswordEncoder passwordEncoder;

    public UserServiceImpl(UserMapper userMapper,
                           UserRoleMapper userRoleMapper,
                           UserJobMapper userJobMapper,
                           RedisUtils redisUtils,
                           UserCacheManager userCacheManager,
                           PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.userRoleMapper = userRoleMapper;
        this.userJobMapper = userJobMapper;
        this.redisUtils = redisUtils;
        this.userCacheManager = userCacheManager;
        this.passwordEncoder = passwordEncoder;
    }

    /**
     * 查询用户信息
     *
     * @param criteria 查询条件s
     * @return 用户信息
     */
    @Override
    public List<User> queryUserinfo(UserQueryCriteria criteria) {
        return userMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(User user) {

        if (userMapper.
                selectOne(lambdaQuery().eq(User::getUserName, user.getUserName())) != null) {
            throw new UserValidateException("用户名:" + user.getUserName() + "已存在");
        }
        if (userMapper.
                selectOne(lambdaQuery().eq(User::getEmail, user.getEmail())) != null) {
            throw new UserValidateException("邮箱:" + user.getEmail() + "已存在");
        }
        if (userMapper.
                selectOne(lambdaQuery().eq(User::getPhone, user.getPhone())) != null) {
            throw new UserValidateException("电话号:" + user.getPhone() + "已存在");
        }
        //单向加密
        user.setPassword(passwordEncoder.encode("123456"));
        save(user);
        //保留用户关联信息
        userRoleMapper.insertData(user.getId(), user.getRoles());
        //保留岗位信息
        userJobMapper.insertData(user.getId(), user.getJobs());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(User user) {
        User Originuser = getById(user.getId());
        User user1 = userMapper.findByUsername(user.getUserName());
        User user2 = userMapper.findByEmail(user.getEmail());
        User user3 = userMapper.findByPhone(user.getPhone());
        if (user1 != null && !Originuser.getId().equals(user1.getId())) {
            throw new BusinessException("用户名称:" + user.getUserName() + "已存在");
        }
        if (user2 != null && !Originuser.getId().equals(user2.getId())) {
            throw new BusinessException("电子邮箱:" + user.getEmail() + "已存在");
        }
        if (user3 != null && !Originuser.getId().equals(user3.getId())) {
            throw new BusinessException("电话号码:" + user.getPhone() + "已存在");
        }
        // 如果用户的角色改变
        if (!user.getRoles().equals(Originuser.getRoles())) {
            redisUtils.del(CacheKey.DATA_USER + user.getId());
            redisUtils.del(CacheKey.MENU_USER + user.getId());
            redisUtils.del(CacheKey.ROLE_AUTH + user.getId());
        }
        // 修改部门会影响 数据权限
        if (!Objects.equals(user.getDepartment(), Originuser.getDepartment())) {
            redisUtils.del(CacheKey.DATA_USER + user.getId());
        }
        Originuser.setDeptId(user.getDepartment().getId());
        Originuser.setUserName(user.getUserName());
        Originuser.setEmail(user.getEmail());
        Originuser.setIsEnable(user.getIsEnable());
        Originuser.setRoles(user.getRoles());
        Originuser.setDepartment(user.getDepartment());
        Originuser.setJobs(user.getJobs());
        Originuser.setPhone(user.getPhone());
        Originuser.setNickName(user.getNickName());
        Originuser.setGender(user.getGender());
        saveOrUpdate(Originuser);
        // 清除缓存
        delCaches(Originuser.getId(), Originuser.getUserName());
        // 更新用户岗位
        userJobMapper.deleteByUserId(user.getId());
        userJobMapper.insertData(user.getId(), user.getJobs());
        // 更新用户角色
        userRoleMapper.deleteByUserId(user.getId());
        userRoleMapper.insertData(user.getId(), user.getRoles());
    }

    /**
     * 删除用户
     *
     * @param ids 用户实体
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Set<Long> ids) {
        for (Long id : ids) {
            // 清理缓存
            User user = getById(id);
            delCaches(user.getId(), user.getUserName());
        }
        userMapper.deleteByIds(ids);
        // 删除用户岗位
        userJobMapper.deleteByUserIds(ids);
        // 删除用户角色
        userRoleMapper.deleteByUserIds(ids);
    }

    /**
     * 清理缓存
     *
     * @param id /
     */
    public void delCaches(Long id, String username) {
        redisUtils.del(CacheKey.USER_ID + id);
        flushCache(username);
    }

    /**
     * 清理 登陆时 用户缓存信息
     *
     * @param username /
     */
    private void flushCache(String username) {
        userCacheManager.cleanUserCache(username);
    }

    /**
     * 导出用户
     *
     * @param criteria 查询条件
     * @param response 流式返回体
     */
    @Override
    public void download(UserQueryCriteria criteria, HttpServletResponse response) throws IOException {
        List<User> userList = queryUserinfo(criteria);
        List<Map<String, Object>> list = new ArrayList<>();
        for (User user : userList) {
            List<String> roles = user.getRoles().stream().map(Role::getName).collect(Collectors.toList());
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("用户名", user.getUserName());
            map.put("角色", roles);
            map.put("部门", user.getDepartment().getName());
            map.put("岗位", user.getJobs().stream().map(Job::getName).collect(Collectors.toList()));
            map.put("邮箱", user.getEmail());
            map.put("状态", user.getIsEnable() ? "启用" : "禁用");
            map.put("手机号码", user.getPhone());
            map.put("修改密码的时间", user.getPwdResetTime());
            map.put("创建日期", user.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 重置密码
     *
     * @param ids 主键
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetUserPassword(Set<Long> ids) {
        String encode = passwordEncoder.encode("123456");
        userMapper.resetPwd(ids, encode);
    }
}
